#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKeyboard.h>
#import <LockInfo/Plugin.h>

#import "framework/FWApplication.h"
#import "framework/FWPlugin.h"
#import "framework/FWCommon.h"
#import "framework/FWPreferences.h"
#import "framework/FWPopupView.h"

#import "PITaskCreate.h"
#import "PITask.h"
#import "PITaskStatus.h"
#import "PITaskIntegration.h"
#import "PITaskNative.h"
#import "PICommon.h"


@implementation PITaskCreate

@synthesize importance, destination;


// ******************************************************************************************
#pragma mark -
#pragma mark Initialisation and object management

- (id)initWithFrame:(CGRect)rect application:(FWApplication*)appl preferences:(FWPreferences*)prefs
{
    if ((self = [super initWithFrame:rect caption:@"New Task/Title" label:@"New Task/Name" prompt:@"New Task/Name Prompt" application:appl preferences:prefs])) {
        NSBundle* bundle = [NSBundle bundleForClass:[self class]];
        
        UISegmentedControl* navControl = [[[UISegmentedControl alloc]
                            initWithItems:
                            [NSArray arrayWithObjects:
                             localize(bundle, @"Importance/None"),
                             localize(bundle, @"Importance/Top"),
                             localize(bundle, @"Importance/High"),
                             localize(bundle, @"Importance/Normal"),
                             localize(bundle, @"Importance/Low"),
                             nil]] autorelease];
        navControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        navControl.segmentedControlStyle = UISegmentedControlStyleBar;
        navControl.tintColor = [UIColor lightGrayColor];
        navControl.selectedSegmentIndex = [prefs intValue:kPIOptionsDefaultImportance withDefault:kPIOptionsDefaultImportanceDefault];
        self.importance = navControl;
        
//        if ([navControl respondsToSelector:@selector(setTitleTextAttributes:forState:)]) {
//            [navControl setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
//                                                [UIFont systemFontOfSize:[UIFont systemFontSize]], UITextAttributeFont,
//                                                [UIColor lightGrayColor], UITextAttributeTextColor,
//                                                [UIColor clearColor], UITextAttributeTextShadowColor,
//                                                nil]
//                                      forState:UIControlStateNormal];
//        }
        

        UISegmentedControl* typeControl = [[[UISegmentedControl alloc]
                                           initWithItems:
                                           [NSArray arrayWithObjects:
                                            localize(bundle, @"New Task/Native"),
                                            localize(bundle, @"New Task/PI"),
                                            nil]] autorelease];
        typeControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        typeControl.segmentedControlStyle = UISegmentedControlStyleBar;
        typeControl.tintColor = [UIColor lightGrayColor];
        self.destination = typeControl;
        typeControl.selectedSegmentIndex = ((PITaskStatus*)self.application.info).newTaskType;
        
        [self layoutView];

        if (!self.application.fwPlugin.isNativeOnly) {
            if ([PITaskNative supportsNativeTasks:self.application])
                [self addSubview:typeControl];
        }
        [self addSubview:navControl];
    }
    
    return self;
}

- (void)dealloc
{
    [importance release];
    [destination release];
    
    [super dealloc];
}

- (void)layoutView
{
    CGSize size = FWGetCurrentScreenSize();
    
    CGRect labelFrame = self.textLabel.frame;
    CGRect textFrame = self.text.frame;
    CGRect importanceFrame = self.importance.frame;
    CGRect destinationFrame = self.destination.frame;
    
    if (size.height > size.width || FWIsDeviceAnIPad()) {
        CGFloat space = FWIsDeviceAnIPad() ? 30 : 15;

        textFrame.origin.y = labelFrame.origin.y + labelFrame.size.height + space;

        importanceFrame.origin.x = textFrame.origin.x;
        importanceFrame.origin.y = textFrame.origin.y + textFrame.size.height + space;
        importanceFrame.size.width = textFrame.size.width;
        
        if (self.destination.superview) {
            if ([PITaskNative supportsNativeTasks:self.application]) {
                destinationFrame.origin.x = textFrame.origin.x;
                destinationFrame.origin.y = importanceFrame.origin.y + importanceFrame.size.height + space;
                destinationFrame.size.width = importanceFrame.size.width;
            }        
        }
    }
    else {
        CGFloat space = 5;
        
        textFrame.origin.y = labelFrame.origin.y + labelFrame.size.height + space;
        
        importanceFrame.origin.x = textFrame.origin.x;
        importanceFrame.origin.y = textFrame.origin.y + textFrame.size.height + space;

        if ([PITaskNative supportsNativeTasks:self.application]) {
            importanceFrame.size.width = importanceFrame.size.width / 7 * 5 - space;

            if (self.destination.superview) {
                destinationFrame.origin.x = importanceFrame.origin.x + importanceFrame.size.width + space;
                destinationFrame.origin.y = importanceFrame.origin.y;
                destinationFrame.size.width = textFrame.size.width - importanceFrame.size.width - space;
            }
        }        
        else {
            importanceFrame.size.width = textFrame.size.width;
        }
    }
    
    self.destination.frame = destinationFrame;
    self.importance.frame = importanceFrame;
    self.text.frame = textFrame;
    self.textLabel.frame = labelFrame;
}

// ******************************************************************************************
#pragma mark -
#pragma mark Layout management - try to look reasonable on both iPhone and iPad

- (void)layoutSubviews
{
    [super layoutSubviews];

    [self layoutView];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Command button callbacks

- (void)doneClicked
{
    NSString* todoTitle = self.text.text;
    
    XLog(@"LI:PITask: New todo to be created: %@", todoTitle);

    if (self.hasFired)
        return;
    else
        self.hasFired = YES;
    
    [self hideKeyboard:YES];
    [self.application.fwPlugin hideToolbar];
    
    PIImportanceType importanceCode = PIImportanceNone;
    switch (self.importance.selectedSegmentIndex) {
        case 0:
            importanceCode = PIImportanceNone;
            break;
        case 1:
            importanceCode = PIImportanceTop;
            break;
        case 2:
            importanceCode = PIImportanceHigh;
            break;
        case 3:
            importanceCode = PIImportanceNormal;
            break;
        case 4:
            importanceCode = PIImportanceLow;
            break;
    }
    
    BOOL native = [PITaskNative supportsNativeTasks:self.application] && (self.destination.selectedSegmentIndex == 0);
    ((PITaskStatus*)self.application.info).newTaskType = self.destination.selectedSegmentIndex;
    
    if (self.application.fwPlugin.isNativeOnly)
        native = true;

    if (native) {
        NSBundle* bundle = [NSBundle bundleForClass:[self class]];
        if ([PITaskNative createTask:todoTitle importance:importanceCode application:self.application]) {
            [self.application.fwPlugin.liPlugin dismissPreview];
            [FWPopupView displayPopupMessage:localize(bundle, @"New Task/Create/Success")
                                     forView:FWLITableView()];
        }
        else {
            [FWPopupView displayPopupMessage:localize(bundle, @"New Task/Create/Error")
                                     forView:self];
            self.hasFired = NO;
        }
    }
    else {
        //[self.application.fwPlugin.liPlugin dismissPreview];
        NSURL* url = [PITaskIntegration urlForNewTask:todoTitle
                                           importance:importanceCode
                                          application:self.application];
        
        XLog(@"LI:%@: Creating new PI task; %@", self.application.resourceName, url);
        
        [self.application.fwPlugin scheduleUnconditionalRefresh];
        [self.application.fwPlugin.liPlugin launchURL:url];
        
#ifdef DEVELOPMENT_MODE
        [self.application.fwPlugin.liPlugin dismissPreview];
#endif
    }
}

@end
